package com.aya.tb;

import com.aya.tb.context.ParameterResolver;
import com.aya.tb.context.ResponseHandler;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

@Service
public class MappingProxy {
    Map<Short, RequestMap> mapMap = new HashMap<>();
    @Resource
    ParameterResolver parameterResolver;

    @Resource
    ResponseHandler responseHandler;

    public void execute(CodeProcessor container, ChannelHandlerContext ctx) {
        try {
            short code = container.code();
            RequestMap requestMap = mapMap.get(code);
            if (requestMap == null) {
                System.out.println("找不到匹配路径");
                return;
            }
            Parameter[] parameters = requestMap.getParameters();
            Object[] parameterObjs = parameterResolver.resolve(parameters,container.body(), ctx);
            Object res = requestMap.getMethod().invoke(requestMap.getBean(), parameterObjs);

            if(res==null){
                return;
            }

            responseHandler.resolve(res,requestMap,ctx,container);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void putRequestMap(Short code, RequestMap requestMap) {
        mapMap.put(code, requestMap);
    }
}
